import React, { PropTypes, Component } from 'react'
import { Button, Toast } from 'antd-mobile'
import { config, helper, myFetch } from '../utils'

/**
 * 带有定时器的`button`
 * 主要用来发送短信验证码
 * 1- 获取注册验证码      2- 获取重置密码验证码
 * 3- 获取绑定银行卡验证码 4- 获取解除银行卡验证码
 */
class TimerButton extends Component {
  constructor(props) {
    super()
    this.state = {
      styleClass: props.styleClass,
      disableVal: props.disableVal,
      text: props.text,
    }
    this.getVerifyCode = this.getVerifyCode.bind(this)
  }

  render() {
    return (
      <Button onClick={() => this.getVerifyCode()} disabled={this.state.disableVal} className={this.state.styleClass} type="primary" inline>{this.state.text || '获取验证码'}</Button>
    )
  }

  getVerifyCode() {
    const { genre } = this.props
    if (genre.mobile) genre.mobile = genre.mobile.replace(/\s/g, '')
    if (genre.mobile !== null) {
      if (!genre.mobile) {
        Toast.fail('手机号码不能为空', 1.2)
        return
      }
      if (!(config.pattern.mobile.test(genre.mobile))) {
        Toast.fail('不是有效的手机号码', 1.2)
        return
      }
    }
    // 禁用按钮点击
    this.setState({
      disableVal: true
    })
    // 请求获取手机验证码
    this.requestForCaptcha(genre)

    const interval = this.props.interval
    let second = interval - 1
    // 启动定时器
    this.it = setInterval(() => {
      this.setState({
        text: `${second} 秒后重发`
      })
      second--
    }, 1000)
    this.to = setTimeout(() => {
      this.setState({
        text: '获取验证码',
        disableVal: false, // 恢复按钮点击
      })
      // 清除定时器
      clearInterval(this.it)
    }, interval * 1000)
  }

  componentWillUnmount() {
    clearInterval(this.it)
    clearTimeout(this.to)
  }

  requestForCaptcha(genre) {
    let options = {
      method: 'POST',
      body: JSON.stringify({
        mobile: genre.mobile
      })
    }
    let op = ''
    let qs = '' // query string
    switch (genre.val) {
      case 1:
        // 获取注册验证码
        op = 'regist'
        qs += 'mobile=' + genre.mobile
        break
      case 2:
        // 获取重置密码验证码
        op = 'password'
        break
      case 3:
        // 获取绑定银行卡验证码
        op = 'binding'
        break
      case 4:
        // 获取解除银行卡验证码
        op = 'unbinding'
        break
    }
    if (op === '') {
      // 类型传递错误
      // 直接返回
      // 无需发送验证码请求
      return
    }
    
    let url = `${config.rootApi}/user/send-mobile-verify-code?${qs}`
    myFetch(url, {})
      .then((rs) => {
        if (rs) {
          Toast.success('验证码发送成功，请注意查收', 2)
        }
      })
      .catch(err => helper.onPromiseError(err))
  }
}

TimerButton.propTypes = {
  interval: PropTypes.number.isRequired,
  text: PropTypes.string,
  styleClass: PropTypes.string,
  disableVal: PropTypes.bool.isRequired,
  genre: PropTypes.object.isRequired,
}

export default TimerButton